import { useState, useEffect, memo } from 'react'
import { Upload, Modal } from 'antd'
import { PlusOutlined } from '@ant-design/icons';

import { uploadSingleImage } from '@/utils/http/linitly.request'
import { warnPrompt } from '@/utils/default.prompt'

const SingleImageUpload = ({
  // 受控组件传入value和onChange，value用于接收传过来的初始值，onChange用于在数据改变时，调用此方法将最新数据赋值
  // 这里的value使用字符串，只传入一个图片的url
  value,
  onChange
}) => {

  const [ imageList, setImageList ] = useState([])

  let initPreviewImage = {
    previewImageUrl: '',
    previewTitle: '',
    previewVisible: false
  }
  const [ previewImage, setPreviewImage ] = useState(initPreviewImage)

  useEffect(() => {
    setImageList(value ? [{ url: value, status: 'done' }] : [])
  }, [value])

  return (
    <div style={{height: '104px'}}>
      <Upload name="file" listType="picture-card" accept=".png,.jpg,.jpeg,.gif" fileList={imageList}
        customRequest={upload} beforeUpload={checkFile} onChange={changeFile} onPreview={preview} >
          {
            imageList.length >= 1 ? null
            :
            <div>
              <PlusOutlined />
              <div style={{ marginTop: 8 }}>点击上传</div>
            </div>
          }
      </Upload>
      <Modal visible={previewImage.previewVisible} title={previewImage.previewTitle} footer={null} onCancel={cancelModal}>
        <img alt="图片加载失败" style={{ width: '100%' }} src={previewImage.previewImageUrl} />
      </Modal>
    </div>
  )

  async function preview(file) {
    console.log('preview')
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    setPreviewImage({
      previewImageUrl: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    })
  }

  function cancelModal() {
    setPreviewImage(initPreviewImage)
  }

  function checkFile(file) {
    // 文件上传之前检查文件大小，如果大于2MB，提示用户
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      warnPrompt('上传的文件需要小于2MB')
      // 返回此值不会显示缩略图
      return Upload.LIST_IGNORE
    }
    return isLt2M
  }

  function changeFile({ fileList }) {
    console.log('change', fileList)
    // 文件改变时，这里只拿到fileList参数，是当前的文件列表
    setImageList(fileList)
    if (fileList && fileList.length > 0) {
      fileList[0].response && onChange?.(fileList[0].response.url)
    }
  }

  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }

  function upload(options) {
    console.log('upload', options)
    uploadSingleImage(options).then((res) => {
      options.onSuccess(res, options.file)
    }).catch((err) => {
      options.onError(err, options.file)
    })
  }
}

export default memo(SingleImageUpload)
